package com.jsjosem.aftersales.ui.worktickets;

import static com.jsjosem.aftersales.constant.Command.REFRESH_TICKET_LIST;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.WorkTicketItemAdapter;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.api.WorkOrderApi;
import com.jsjosem.aftersales.data.response.PageResponse;
import com.jsjosem.aftersales.data.response.UserInfoResponse;
import com.jsjosem.aftersales.data.response.WorkOrderResponse;
import com.jsjosem.aftersales.data.response.WorkTicket;
import com.jsjosem.aftersales.listener.IListener;
import com.jsjosem.aftersales.listener.ListenerManager;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.utils.PageUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import retrofit2.Call;
import retrofit2.Retrofit;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TicketListItemFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TicketListItemFragment extends Fragment implements IListener {

    private Context context;
    private RecyclerView recyclerView;
    private WorkTicketItemAdapter workTicketItemAdapter;
    private List<WorkTicket> workTickets = new ArrayList<>();
    private SmartRefreshLayout smartRefreshLayout;
    private final static int PAGE_SIZE = 10;
    private int currentPage = 1;
    private int totalPage;
    private View view;
    private Retrofit retrofit;
    private Dialog loadingDialog;
    private String dateType;
    private String dateStart;
    private String dateEnd;
    private String aboutMe;
    private String status;
    private static Map<String, String> statusMap;

    static {
        statusMap = new HashMap<>();
        statusMap.put("未完成", "un_complete");
        statusMap.put("已创建", "un_assign");
        statusMap.put("已指派", "assigned");
        statusMap.put("已接受", "accept");
        statusMap.put("已开始", "process");
        statusMap.put("已完成", "complete");
    }

    private String type;

    public TicketListItemFragment(String status) {
        this.status = status;
    }

    public static TicketListItemFragment newInstance(String status) {
        return new TicketListItemFragment(status);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initView(inflater, container);
        initData();
        initPageList();
        loadMore();
        return view;
    }

    private void initPageList() {
        workTicketItemAdapter = new WorkTicketItemAdapter(context, workTickets);
        workTicketItemAdapter.setOnItemClickListener((v, position) -> {
            Intent intent = new Intent(getContext(), WorkTicketsInfoActivity.class);
            intent.putExtra("data", new Gson().toJson(workTickets.get(position)));
            startActivity(intent);
        });
        recyclerView.setAdapter(workTicketItemAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
    }

    private void initView(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_page_list, container, false);
        context = view.getContext();
        smartRefreshLayout = view.findViewById(R.id.refreshLayout);
        smartRefreshLayout.setEnableAutoLoadMore(false);
        recyclerView = view.findViewById(R.id.ticket_recycler_view);
        retrofit = RetrofitClient.getInstance();
        ListenerManager.getInstance().registerListener(this);
    }

    private void initData() {
        loadingShow();
        WorkOrderApi workOrderApi = retrofit.create(WorkOrderApi.class);
        Call<PageResponse<WorkOrderResponse>> workOrderCall = workOrderApi.getByPage(dateType, dateStart, dateEnd, aboutMe, statusMap.get(status), type, currentPage, PAGE_SIZE);
        AsyncRequest<PageResponse<WorkOrderResponse>> request = new AsyncRequest<>();
        request.sendRequest(workOrderCall, (res) -> {
            List<WorkOrderResponse> data = res.getData();
            Long total = res.getCount();
            totalPage = PageUtils.totalPage(PAGE_SIZE, total);
            if (CollUtil.isNotEmpty(data)) {
                for (WorkOrderResponse workOrder : data) {
                    WorkTicket workTicket = new WorkTicket();
                    workTicket.setAddress(workOrder.getmAddress());
                    workTicket.setTicketType(workOrder.getmType());
                    workTicket.setTicketState(workOrder.getmStatus());
                    workTicket.setTicketCode(workOrder.getmWoNumber());
                    workTicket.setId(workOrder.getmId());
                    workTicket.setScheduleTime(workOrder.getmPlanAt());
                    List<UserInfoResponse> userInfoResponses = workOrder.getmUsers();
                    for (int i = 0; i < userInfoResponses.size(); i++) {
                        if (userInfoResponses.get(i).getIsMaster() == 1) {
                            workTicket.setHandlers(userInfoResponses.get(i).getUser().getRealname());
                        }
                    }
                    workTicket.setCustomerName(workOrder.getmContactName());
                    workTicket.setOriginalTicket(workOrder);
                    workTickets.add(workTicket);
                    smartRefreshLayout.finishRefresh();
                }
                // 数据加载好后，初始化列表页
                int size = workTickets.size();
                workTicketItemAdapter.notifyItemRangeChanged(size - 1 < 0 ? 0 : size, data.size());
            }
            loadingDialog.dismiss();
        }, msg -> {
            loadingDialog.dismiss();
            Toast.makeText(context, msg.toString(), Toast.LENGTH_LONG).show();
        });
    }

    public void loadingShow() {
        loadingDialog = new Dialog(context, R.style.normal_dialog_style);
        View loadingView = View.inflate(context, R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }

    private void loadMore() {
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            /**
             * 加载更多
             * @param refreshLayout
             */
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                // 没有下一页了
                if (totalPage <= currentPage) {
                    smartRefreshLayout.finishLoadMoreWithNoMoreData();
                }
                ++currentPage;
                initData();
                smartRefreshLayout.finishLoadMore();
            }

            /**
             * 下拉刷新
             * @param refreshLayout
             */
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                int size = workTickets.size();
                workTickets.clear();
                workTicketItemAdapter.notifyItemRangeRemoved(0, size);
                initData();
                smartRefreshLayout.finishRefresh();
            }
        });
    }

    @Override
    public void notifyAllActivity(int flag, String data, String message) {
        if (flag == REFRESH_TICKET_LIST) {

            if (StrUtil.equalsAny(data, "week", "month")) {
                dateType = data;
            }

            if (StrUtil.equalsAny(data, "department", "assist", "master", "create")) {
                aboutMe = data;
            }

            String[] split = data.split(":");
            String dataKey = split[0];

            if (StrUtil.equals(dataKey, "date")) {
                String[] dateArr = split[1].split(",");
                dateStart = dateArr[0];
                dateEnd = dateArr[1];
            }
            initData();
        }
    }
}